/**
 * @author Nicolas Latore
 * @author Giuseppe Mendola
 * @author Virginie Blancs
 */

package sa4

import javax.servlet.http._
import scala.xml._
import javax.servlet.ServletConfig
import sa4.form._
import sa4.session._
import sa4.template._
import sa4.routing._
import sa4.persistence._
import org.squeryl.KeyedEntity
import org.squeryl.SessionFactory
import org.squeryl.Session
import org.squeryl.adapters.H2Adapter
import scala.util.matching.Regex
import org.squeryl.adapters.H2Adapter
import java.sql.Timestamp
import java.sql.Date
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.dsl.ast.LogicalBoolean
import org.squeryl.annotations.OptionType
import java.io.FileInputStream
import javax.imageio.ImageIO
import java.net.URL

// This is a very simple Scala servlet.
// If you rename this class, you must also change the file
// src/main/webapp/WEB-INF/web.xml to use the new name.
class Framework extends HttpServlet {
  type HandlerFunction = (HttpServletRequest, HttpServletResponse) => Unit

  val routing = new Routing()
  val template = new Template()
  val session = new SessionManagement()
  val persistence = new Persistence()
  val form = new Form(this)

  /**
   * Function that initializes the servlet
   * @param config 		a SerletConfig that contain the configuration for the servlet
   */
  override def init(config: ServletConfig) {
    super.init(config)
    //Starting the database
    Class.forName("org.h2.Driver")

    persistence.startDB

    transaction {
      UsiBets.drop
    }

    transaction {
      UsiBets.create
    }
  }

  /**
   * Function that manages requests and response on the server
   * @param req 	an HttpServletRequest to the servlet
   * @param resp 	an HttpSErvletResponse from the servlet
   */
  override def service(req: HttpServletRequest, resp: HttpServletResponse) {
    //Session setup
    var currentContext = session.getCurrentContext
    currentContext = session.newContext(req, resp, currentContext)
    var cc = currentContext().session
    cc.setMaxInactiveInterval(60)

    //Routing dispatch
    if (routing.tableDispatch(req, resp))
      return
    resp.sendError(HttpServletResponse.SC_NOT_FOUND)

  }
}